#include "app.h"
#include "TIMER\timer.h"
/* variable use for snake*/
extern unsigned char stateMove;
extern unsigned char sizeSnake;

extern unsigned char dataP0[sizeFloor];
extern unsigned char dataP1[sizeFloor];
extern unsigned char snake_part[64];
extern unsigned char xyzVictim;

/*temp variable*/
extern unsigned char xtemp;
extern unsigned char ytemp;
extern unsigned char ztemp;
unsigned char xyztemp;
extern unsigned char check;
extern int i;



unsigned char mergeXYZ(unsigned char x,unsigned char y,unsigned char z){

	if(x>3||y>3||z>3||x<0||y<0||z<0){
		//return 0xff;
	}else{
		xtemp =((x<<4)|(y<<2)|z);
		return xtemp;
	}
}
//unsigned char splitXYZ(unsigned char xyz, unsigned char x,unsigned char y,unsigned char z){
//	x=(xyz%64)/16;
//	y=(xyz%16)/4;
//	z=xyz%4;
//	
//	if(x>3||y>3||z>3||x<0||y<0||z<0){
//	   return 0;
//	}else{
//		return 1;
//	}
//}
void initSnake(){
	sizeSnake=1;
	stateMove=rand()%6+1;
	xyzVictim=mergeXYZ(	rand()%4,rand()%4,rand()%4);
	snake_part[0]=mergeXYZ(	2,2,2);
	xyztemp=getNextPosition(stateMove);
	eat(xyztemp);
}
void moveSnake(){
		xyztemp=getNextPosition(stateMove);
		check=0; //Normal
		/***** Check accident *****/
		for(xtemp=0;xtemp<sizeSnake;xtemp++){
			if(xyztemp==snake_part[xtemp])  
				check=ACCIDENT;
		}
		/***** Check eat Victim *****/
		if (xyztemp==xyzVictim)
			check=EATVICTIM;
		/***** -o0o0o0o('.') *****/ 
		switch(check){
			case 0: //move normal
				for(i=sizeSnake-1;i>0;i--){
					snake_part[i]=snake_part[i-1];  
				}
					snake_part[0]=xyztemp;
					//snake_part[sizeSnake-1]=0;
				break;
			case ACCIDENT:
				// Notice LOST
				// your code here
				break;
			case EATVICTIM:
				eat(xyzVictim);
				//check WIN
				if(sizeSnake>=PARTS2WIN){
					// Notice WIN
					// your code here
				}

				//new Victim;
				do{
					check=0;
					xyztemp=mergeXYZ(	rand()%4,rand()%4,rand()%4);
					for(xtemp=0;xtemp<sizeSnake;xtemp++){
						if(xyztemp==snake_part[xtemp])  
							check=ACCIDENT;
					}
				} while(check==ACCIDENT);
				xyzVictim=xyztemp;
				break;
		}
	 
}
unsigned char getNextPosition(unsigned char state){
		xtemp=(snake_part[0]%64)/16;
		ytemp=(snake_part[0]%16)/4;
		ztemp=snake_part[0]%4;
	switch(state){
		case UP:
			ztemp=(ztemp+1)%4;
			break;
		case DOWN:
			ztemp=(ztemp+3)%4;
			break;
		case LEFT:
			xtemp=(xtemp+3)%4;
			break;
		case RIGHT:
			xtemp=(xtemp+1)%4;
			break;
		case AHEAD:
			ytemp=(ytemp+1)%4;
			break;
 		case BACK:
			ytemp=(ytemp+3)%4;
			break;
	}
	xyztemp=mergeXYZ(xtemp,ytemp,ztemp);
	return xyztemp;
}
void eat(unsigned char victim){	  
  		for(i=sizeSnake;i>=0;i--){
			snake_part[i+1]=snake_part[i];  
		}
		snake_part[0]=victim;
		sizeSnake++;


}

